//获取应用实例
const app = getApp();
import requestUtil from '../../../utils/requestUtil';
import _DuoguanData from '../../../utils/data';
import dg from '../../../utils/dg';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // count: ,
    seconds: 120,
    timer: 120,
    use_time: 0,
    is_show: 0,
    info_show: false,
    qlist: [],
    current: 1,   //当前题号
    next: 0,
    right: [],    //答题正确结果集
    wrong: [],   //答题错误结果集
    btext: '下一题',
    info_need: 0,  //是否需要提交个人信息
    is_put: 0,   //答题是否已结束
    is_sub: 0,   //是否已提交
    rlog: [],    //答题记录
    score: 0,    //得分
    active_id: 13,
    show_score: false, //显示题目得分
    is_disabled: false,  //单选/复选框是否可用
    is_answer: 0, //是否已答题
    is_right: 1, //答对还是答错 
    o_index: 0, //  选项索引
    oindex_arr: [], //  多选题选项索引
    answer_arr: []   // 多选题答案数组
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    let active_id = options.active_id ? options.active_id : 13
    that.setData({ active_id: active_id });
    let requestData = {};
    requestData.active_id = active_id;
    requestUtil.get(_DuoguanData.duoguan_host_api_url + "/index.php/addon/DuoguanWenda/ApiNew/get_question.html", requestData, (data) => {
      console.log(data);
      //活动未开始或已结束时，跳转到首页
      if (data.is_end == 1 || data.is_start == 0 || data.re_num <= 0) {
        wx.switchTab({
          url: '../index/index'
        })
        return;
      }
      that.setData({
        count: data.count,
        seconds: data.seconds,
        timer: data.seconds,
        is_show: 1, //控制弹窗显示
        qlist: data.lists,
        time: data.seconds,
        info_need: data.info_need, //是否需要填写个人信息
        info_msg:data.info_msg
      });
    }, this, {});

    //先隐藏分享按钮，等加载完数据后再显示分享
    if (wx.hideShareMenu) wx.showShareMenu();

    //获取分享信息
    requestUtil.get(_DuoguanData.duoguan_get_share_data_url, { mmodule: 'DuoguanWenda' }, (info) => {
      this.shareInfo = info;
      if (wx.showShareMenu) wx.showShareMenu();   //显示分享按钮

    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    this.shareInfo = this.shareInfo || {};
    const title = this.shareInfo.title || '全民答题，不服来战';
    const desc = this.shareInfo.desc || '';
    return {
      title: title,
      path: 'pages/wenda/answer/answer',
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  /**
  * 单选按钮点击事件
  */
  radioChange: function (e) {
    let that = this;
    that.setData({ is_disabled: true });   //设置题目选择项只读模式

    let all_score = that.data.score;  //当前得分
    let current = that.data.current;   //当前题号 
    let option_val = e.detail.value.split('_'); //单选框的值分割成数组
    let val = option_val[0]; //选择大答案
    let o_index = option_val[1];  //选择答案索引
    let answer = e.currentTarget.dataset.id;    //正确答案
    let this_score = e.currentTarget.dataset.key;   //本题分值
    let right = that.data.right;    //答题正确结果集
    let wrong = that.data.wrong;    //答题错误结果集
    let next = e.currentTarget.dataset.next;

    if (val == answer) {    //答题正确
      right.push(current);
      that.setData({
        score: parseInt(all_score) + parseInt(this_score),  //答题正确，得分添加
      });

      that.setData({ is_disabled: true, is_answer: 1, is_right: 1, o_index: o_index });
    } else {    //答题错误
      wrong.push(current);
      that.setData({ is_disabled: true, is_answer: 1, is_right: 0, o_index: o_index });
    }

    if (current == that.data.count) {    //最后一题，答错直接提交结果
      that.setData({
        use_time: that.data.timer - that.data.seconds,
        is_put: 1  //倒计时不提交数据
      });
      if (that.data.info_need == 1) {
        that.setData({
          next: next,
          is_show: 2
        });
      } else {
        setTimeout(function () {  //选择答案1后跳转至下一题
          that.formSubmit();
        }, 1000);
      }
    } else {
      setTimeout(function () {  //选择答案1后跳转至下一题
        that.setData({
          next: next,
          current: current + 1,
          is_answer: 0,
          is_disabled: false
        })
      }, 1000);
    }
  },

  /**
   * 复选框点击事件
  */
  checkboxChange: function (e) {
    let that = this;
    let all_score = that.data.score;  //当前得分
    let this_score = e.currentTarget.dataset.key;   //本题分值
    let current = that.data.current;   //当前题号
    let right = that.data.right;    //答题正确结果集
    let wrong = that.data.wrong;    //答题错误结果集
    let next = e.currentTarget.dataset.next;
    let val = e.detail.value; //复选框选项
    let answer = e.currentTarget.dataset.id;    //正确答案
    
    let opt_arr = that.data.qlist[next - 1]['option'];  //题目选项
    
    let oindex_arr = [];    
    let answer_arr = [];
    for (var i = 0; i < val.length; i++) {    //遍历只取问题答案 选项
      let arr = val[i].split('_');
      let is_answer = answer.indexOf(arr[0]);
      val[i] = arr[0];
      oindex_arr[arr[1]] = arr[1];
    }
    
    for(var i=0;i<opt_arr.length;i++){
      let opt = answer.indexOf(opt_arr[i][0]);
      if (opt != -1) {
        answer_arr[i] = opt_arr[i][0];
      }
    }

    if (val.sort().toString() == answer.sort().toString()) {  //答题完全正确
      right.push(current);
      that.setData({
        score: parseInt(all_score) + parseInt(this_score),
      });
      that.setData({ is_disabled: true, is_answer: 1, is_right: 1, oindex_arr: oindex_arr, answer_arr: answer_arr });

      if (current == that.data.count) {    //最后一题，答完后提交结果
        that.setData({
          use_time: that.data.timer - that.data.seconds,
          is_put: 1  //倒计时不提交数据
        });
        if (that.data.info_need == 1) {
          that.setData({
            next: next,
            is_show: 2
          });
        } else {
          setTimeout(function () {  //选择答案1后跳转至下一题
            that.formSubmit();
          }, 1000);
        }
      } else {
        setTimeout(function () {  //选择答案1后跳转至下一题
          that.setData({
            next: next,
            current: current + 1,
            is_answer: 0,
            is_disabled: false
          })
        }, 1000);
      }
    } else {
      for (var i = 0; i < val.length; i++) {    //遍历只取问题答案 选项
        let is_exist = answer.indexOf(val[i]);
        if (is_exist == -1) { //答题错误
          wrong.push(current);
          that.setData({ is_disabled: true, is_answer: 1, is_right: 0, oindex_arr: oindex_arr, answer_arr: answer_arr });

          if (current == that.data.count) {    //最后一题，答错直接提交结果
            that.setData({
              use_time: that.data.timer - that.data.seconds,
              is_put: 1  //倒计时不提交数据
            });
            if (that.data.info_need == 1) {
              that.setData({
                next: next,
                is_show: 2
              });
            } else {
              setTimeout(function () {  //选择答案1后跳转至下一题
                that.formSubmit();
              }, 1000);
            }
          } else {
            setTimeout(function () {  //选择答案1后跳转至下一题
              that.setData({
                next: next,
                current: current + 1,
                is_answer: 0,
                is_disabled: false
              })
            }, 1000);
          }
          return;
        }
      }
      that.setData({ is_disabled: true, is_answer: 1, is_right: 2, oindex_arr: oindex_arr, answer_arr: answer_arr });
    }

  },

  /**
   * 提交结果，跳转页面
   */
  formSubmit: function (e) {
    if (this.data.is_sub == 1) {
      wx.showToast({
        title: '您的结果已提交，不能重复提交',
        icon: 'none',
        duration: 2000
      })
      return;
    }

    let count = this.data.right.length;  //答对的题数
    let all_count = this.data.count;    //题目数量
    let wrong_count = this.data.wrong.length; //答错的题数

    let requestData = {};
    requestData.count = count;    //答对数
    requestData.wrong = wrong_count;  //答错数
    requestData.skip = all_count - wrong_count - count;   //跳过数
    requestData.use_time = this.data.use_time;    //用时
    requestData.score = this.data.score;  //最后得分
    requestData.active_id = this.data.active_id;  //活动id
    if (e) {
      requestData.name = e.detail.value.name;
      requestData.phone = e.detail.value.phone;
      requestData.desc = e.detail.value.desc;
      requestData.is_add = 1;
    }

    //提交结果
    requestUtil.post(_DuoguanData.duoguan_host_api_url + "/index.php/addon/DuoguanWenda/ApiNew/add_info.html", requestData, (data) => {
      this.setData({
        is_sub: 1, //  设置结果已提交 
      });
      
      if(data!==1){
        //跳转页面
        wx.redirectTo({
          url: '../result/result?active_id=' + this.data.active_id,
        })
      }else{
        wx.showModal({
          title: '提示信息',
          content: '您的答题机会已用完',
          success: function (res) {
            if (res.confirm) {
              wx.switchTab({
                url: '../index/index'
              })
            } else if (res.cancel) {
              wx.switchTab({
                url: '../index/index'
              })
            }
          }
        })
      }
    }, this, {});
  },

  /**
     * 关闭弹窗
     */
  isClose: function () {
    this.setData({
      is_show: false
    });
    this.countdown();
  },

  /* 秒级倒计时 */
  countdown: function () {
    var that = this;
    var seconds = that.data.seconds;
    var is_put = that.data.is_put;
    if (is_put == 0) {  //倒计时已停止时
      if (seconds == 0) {
        that.setData({
          seconds: 0,
          use_time: that.data.timer,  //用时
        });
        if (that.data.info_need == 1) {
          that.setData({
            is_show: 2
          });
        } else {
          that.formSubmit();
        }
        return;
      }
      var timer = setTimeout(function () {
        that.setData({
          seconds: seconds - 1
        });
        that.countdown();
      }, 1000);
    }
  },
  nav(e) {
    nav.navTo(e.currentTarget.dataset.url, e.currentTarget.dataset.param)
  },

  tabNav(e) {
    nav.swithTo(e.currentTarget.dataset.url, e.currentTarget.dataset.param)
  },

})